/**
 * 后端验证微信服务器
 * sha
 *    摘要算法，我通过明文可以可以摘要出密文，反向不可达
 *    雪崩效应， 
 *    md5 sha
 * 
 *  我们验证了微信 
 */

var router = {}

router.get('/getTokens', async ctx => {
  const wxDomain = 'https://api.weixin.qq.com'
  const path = ''


  const res = await axios.get(url)
  ctx.body = res.data

  // 微信验证的我们
})
router.get("/getFollow", async ctx => {
  const url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET'
  const res = await axios.get(url)
  
  ctx.body = res.data

})


const wechatapi = require('co-wechat-api')
const api = new WechatAPI(conf.appid, conf.appsecret);
router.get('/getFollowers', async ctx => {
  const res = await api.getFollowers()
  ctx.body = res
})

const OAuth = require('co-wechat-oauth')
const oauth = new OAuth()

// 生成引导用户点击的url
router.get('/wxAuthorize', async ctx=>{
  const state = ctx.query.id
  // 获取本机地址 http://3fjdks34.ngrok.io/wxAuthorize
  console.log('ctx...' + ctx.href)

  // 建立目标地址 回调地址
  let redirectUrl = ctx.href
  redirectUrl = redirectUrl.replace('wxAuthorize', 'wxCallback')
  const scope = 'snsapi_userinfo'
  // 重定向到微信接口 https://open.weixin.qq.com/connect/oauth2/authorize?appid=fdfd&redirect_url
  const url = oauth.getAuthorizeURL(redirectUrl, state, scope)
  console.log('url:'+url)
  ctx.redirect(url)
})

router.get('/wxCallback', ctx => {
  console.log('Callback...')
  const code = ctx.query.code // 授权码
  
  // 收到授权码code后，再次向认证服务器换token
  const token = await oauth.getAccessToken(code)
  const accessToken = token.data.access_token
  const openid = token.data.openid

  console.log('accessToken', accessToken)
  console.log('openid', openid)

  ctx.redirect('/?openid=' + openid)
})

/**
 * 多端应用 flutter taro
 *  
 * 
 */ 

router.get('getUser', async ctx=>{
  const openid = ctx.query.openid
  const userInfo = await oauth.getUser(openid)
  ctx.body = userInfo
})

router.get('getJSConfig', async ctx => {
  const res = await api.getJsConfig(ctx.query)
  ctx.body = res
})